<template>
  <div class="modal-overlay" v-show="show" @click.self="$emit('close')">
    <div class="modal">
      <h3>修改学生信息</h3>
      <form @submit.prevent="submitForm">
        <p>
          <label>姓名：</label>
          <input v-model="form.name" type="text" required />
        </p>
        <p>
          <label>年龄：</label>
          <input v-model="form.age" type="number" required />
        </p>
        <p>
          <label>性别：</label>
          <label><input type="radio" value="男" v-model="form.gender" /> 男</label>
          <label><input type="radio" value="女" v-model="form.gender" /> 女</label>
        </p>
        <p>
          <label>原照片：</label><br />
          <img v-if="student.photo" :src="student.photo" alt="学生照片" class="student-photo" />
        </p>
        <p>
          <label>新照片（可选）：</label>
          <input type="file" @change="handleFileChange" />
          <br />
          <small>如果不上传，照片不会更新</small>
        </p>
        <div class="actions">
          <button type="submit">提交</button>
          <button type="button" @click="$emit('close')">取消</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, watch } from 'vue'
import axios from 'axios'

const props = defineProps({
  show: Boolean,
  student: {
    type: Object,
    required: true
  }
})

const emits = defineEmits(['close', 'success'])

const form = reactive({
  id: '',
  name: '',
  age: '',
  gender: '男',
  photofile: null // 新上传文件，可为空
})

// 当父组件传入 student 时赋值表单
watch(
  () => props.student,
  (newStu) => {
    if (newStu) {
      form.id = newStu.id
      form.name = newStu.name
      form.age = newStu.age
      form.gender = newStu.gender
      form.photofile = null // 清空旧文件
    }
  },
  { immediate: true }
)

const handleFileChange = (e) => {
  form.photofile = e.target.files[0] || null
}

const submitForm = async () => {
  try {
    const formData = new FormData()
    formData.append('id', form.id)
    formData.append('name', form.name)
    formData.append('age', form.age)
    formData.append('gender', form.gender)
    if (form.photofile) {
      formData.append('photofile', form.photofile)
    }

    const res = await axios.put('http://localhost:8080/student/update', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })

    if (res.data.code === 1) {
      alert('更新成功')
      emits('success')
      emits('close')
    } else {
      alert('更新失败: ' + res.data.msg)
    }
  } catch (err) {
    console.error('更新出错:', err)
    alert('提交失败，请检查服务器')
  }
}
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal {
  background: white;
  padding: 20px;
  border-radius: 6px;
  min-width: 320px;
}
.student-photo {
  width: 120px;
  height: auto;
  margin-top: 6px;
  border: 1px solid #ccc;
}
.actions {
  margin-top: 12px;
}
.actions button {
  margin-right: 8px;
}
</style>
